package com.emm.yixun.customer.service.impl;
import java.util.List;

import javax.jws.WebService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.basic.service.CustomerProjectQuestionService;
import com.emm.yixun.basic.service.DataPermissionService;
import com.emm.yixun.basic.service.ProjectAnswerService;
import com.emm.yixun.basic.service.ProjectQuestionService;
import com.emm.yixun.basic.service.ProjectQuestionnaireService;
import com.emm.yixun.basic.service.ProjectService;
import com.emm.yixun.basic.service.QuestionnaireAnswerService;
import com.emm.yixun.basic.service.QuestionnaireQuestionService;
import com.emm.yixun.common.constant.SysConstants;
import com.emm.yixun.common.exception.ResponseCode;
import com.emm.yixun.common.exception.XFUNExceptionCode;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.ProjectAnswer;
import com.emm.yixun.common.model.ProjectQuestion;
import com.emm.yixun.common.model.ProjectQuestionnaire;
import com.emm.yixun.common.model.ProjectQuestionnaireInfo;
import com.emm.yixun.common.model.QuestionnaireAnswer;
import com.emm.yixun.common.model.QuestionnaireQuestion;
import com.emm.yixun.common.model.dto.CustomerProjectQuestionDto;
import com.emm.yixun.common.model.dto.ProjectAnswerDto;
import com.emm.yixun.common.model.dto.ProjectQuestionDto;
import com.emm.yixun.common.model.dto.ProjectQuestionnaireDto;
import com.emm.yixun.common.model.dto.QuestionnaireAnswerDto;
import com.emm.yixun.common.model.dto.QuestionnaireQuestionDto;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.customer.service.ProjectQuestionnaireServiceFacade;

@Service("projectQuestionnaireServiceFacade")
@WebService(name="com.emm.yixun.customer.service.ProjectQuestionnaireServiceFacade")
public class ProjectQuestionnaireServiceFacadeImpl implements ProjectQuestionnaireServiceFacade{
	private  final Logger   logger = LoggerFactory.getLogger(this.getClass()); 
	
	@Autowired
	private ProjectQuestionnaireService service;
	
	@Autowired
	private ProjectAnswerService projectAnswerService;
	
	@Autowired
	private QuestionnaireQuestionService questionnaireQuestionService;
	
	@Autowired
	private QuestionnaireAnswerService questionnaireAnswerService;
	
	@Autowired
	private ProjectQuestionService projectQuestionService;
	
	@Autowired
	private ProjectService projectService;
	
	@Autowired
	private CustomerProjectQuestionService customerProjectQuestionService;
	
	@Autowired
	private DataPermissionService dataPermissionService;

	@Override
	public Response<ProjectQuestionnaireDto> save(ProjectQuestionnaireDto dto) {
		Response<ProjectQuestionnaireDto> response=new Response<ProjectQuestionnaireDto>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			ProjectQuestionnaireDto mDto=service.create(dto);
			if(null==mDto){
				response.fail("80000", "保存数据错误");
				return response;
			}
			response.success(mDto);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<Integer> updateByPrimaryKey(ProjectQuestionnaireDto dto,Boolean selective) {
		Response<Integer> response=new Response<Integer>();
		try {
			if(null==selective || null==dto || null==dto.getId()){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("更新"));
				return response;
			}
			
			if(selective){
				int count=service.update(dto);
				if(count>0){
					response.success(Integer.valueOf(count));
					//当编辑内容为删除时，同时删除问卷问题及答案
					if(DelFlagEnum.DEL.getNo().equals(dto.getDelFlag())){
						deleteQuestion(dto.getId());
					}else{
					    //修改问卷问题的项目ID
					    editQuesion(dto.getId(), dto.getProjectId());
					}
				}else{
					response.fail("90001", "更新数据失败");
				}
			}else{
				response.fail("90000", "暂未实现,修改参数selective=true即可");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}",e);
		}
		return response;
	}
	/**
	 * 修改问题项目ID
	 * @param id
	 * @param projectId
	 */
	private void editQuesion(Long id, Long projectId){
	    ProjectQuestionDto entity = new ProjectQuestionDto();
        entity.setProjectQuestionnaireId(id);
        List<ProjectQuestion> list = projectQuestionService.selectListByDto(entity);
        for(ProjectQuestion qq : list){
            ProjectQuestionDto dto = new ProjectQuestionDto();
            dto.setId(qq.getId());
            dto.setProjectId(projectId);
            projectQuestionService.update(dto);
        }
	}
	/**
	 * 逻辑删除问卷问题
	 */
	private void deleteQuestion(Long id){
		ProjectQuestionDto entity = new ProjectQuestionDto();
		entity.setProjectQuestionnaireId(id);
		List<ProjectQuestion> list = projectQuestionService.selectListByDto(entity);
		for(ProjectQuestion qq : list){
			ProjectQuestionDto dto = new ProjectQuestionDto();
			dto.setId(qq.getId());
			dto.setDelFlag(DelFlagEnum.DEL.getNo());
			projectQuestionService.update(dto);
			//逻辑删除问卷答案
			deleteAnswer(qq.getId());
		}
	}
	/**
	 * 逻辑删除问卷答案
	 */
	private void deleteAnswer(Long id){
		ProjectAnswerDto entity = new ProjectAnswerDto();
		entity.setProjectQuestionId(id);
		List<ProjectAnswer> list = projectAnswerService.selectListByDto(entity);
		for(ProjectAnswer qa : list){
			ProjectAnswerDto dto = new ProjectAnswerDto();
			dto.setId(qa.getId());
			dto.setDelFlag(DelFlagEnum.DEL.getNo());
			projectAnswerService.update(dto);
		}
	}

	@Override
	public Response<Integer> deleteByPrimaryKey(Long id) {
		Response<Integer> response=new Response<Integer>();
		try {
			if(null==id){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("删除"));
				return response;
			}
			ProjectQuestionnaireDto mDto=new ProjectQuestionnaireDto();
			mDto.setId(id);
			int count=service.destroy(mDto);
			if(count>0){
				response.success(Integer.valueOf(count));
			}else{
				response.fail("90001", "删除数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("删除数据错误：{}",e);
		}
		return response;
	}
	
	@Override
	public Response<ProjectQuestionnaire> findById(Long id) {
		Response<ProjectQuestionnaire> response=new Response<ProjectQuestionnaire>();
		try {
			if(null==id){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			ProjectQuestionnaire entity=service.selectById(id);
			if(null==entity){
				response.fail("90001", "主键查询数据失败");
			}else{
				response.success(entity);
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}",e);
		}
		return response;
	}
	
    @Override
	public Response<ProjectQuestionnaireInfo> findByIdInfo(Long id) {
		Response<ProjectQuestionnaireInfo> response=new Response<ProjectQuestionnaireInfo>();
		try {
			if(null==id){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			ProjectQuestionnaire entity=service.selectById(id);
			if(null==entity){
				response.fail("90001", "主键查询数据失败");
			}else{
				//查询问卷填写人数
				ProjectQuestionnaireInfo info = new ProjectQuestionnaireInfo();
				BeanUtils.copyProperties(entity, info);
				info.setFillInNum(fillInNum(id));
				response.success(info);
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}",e);
		}
		return response;
	}
    //查询问卷填写人数
    private int fillInNum(Long id){
    	CustomerProjectQuestionDto dto = new CustomerProjectQuestionDto();
		dto.setProjectQuestionnaireId(id);
		int fillInNum = customerProjectQuestionService.fillInNum(dto);
		return fillInNum;
    }

	@Override
	public ResponseList<ProjectQuestionnaire> findByDto(ProjectQuestionnaireDto dto) {
		ResponseList<ProjectQuestionnaire> response=new ResponseList<ProjectQuestionnaire>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<ProjectQuestionnaire> list=service.selectListByDto(dto);
			if(null==list){
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Page<ProjectQuestionnaire> findPageByDto(ProjectQuestionnaireDto dto, Integer begin,Integer row) {
		Page<ProjectQuestionnaire> response=new Page<ProjectQuestionnaire>();
		try {
			if(null==dto || null==begin || null==row){
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<ProjectQuestionnaire> page = service.getPageModel(dto, begin, row);
			if(null==page.getRows()){
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response=page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}",e);
		}
		return response;
	}
	
	@Override
	public Page<ProjectQuestionnaireInfo> findPageInfoByDto(ProjectQuestionnaireDto dto, Integer begin,Integer row) {
		Page<ProjectQuestionnaireInfo> response=new Page<ProjectQuestionnaireInfo>();
		try {
			if(null==dto || null==begin || null==row){
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			// 数据权限
			if (SysConstants.openDataPermission) {
				String dataPermission = dataPermissionService.dataPermissionCondition(dto.getPermissionUserId(),
						dto.getResourcesCode(), dto.getPrefix(), dto.getColumnName());
				String[] dataPermissionArr = dataPermission.split(":");
				if ("00".equals(dataPermissionArr[0])) {
					response.setErrorMsg(XFUNExceptionCode.USER_PRODUCTNOEXIST.getDesin());
					response.setSuccess(false);
					return response;
				}
				dto.setDataPermission(dataPermissionArr[1]);
			}
			
			Page<ProjectQuestionnaireInfo> page = service.getPageModelInfo(dto, begin, row);
			if(null==page.getRows()){
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response=page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}",e);
		}
		return response;
	}
	
	@Override
	public Page<ProjectQuestionnaireInfo> findCustomerPageInfoByDto(ProjectQuestionnaireDto dto, Integer begin,Integer row) {
		Page<ProjectQuestionnaireInfo> response=new Page<ProjectQuestionnaireInfo>();
		try {
			if(null==dto || null==begin || null==row){
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			
			// 数据权限
			if (SysConstants.openDataPermission) {
				String dataPermission = dataPermissionService.dataPermissionCondition(dto.getPermissionUserId(),dto.getResourcesCode(), dto.getPrefix(), dto.getColumnName());
				String[] dataPermissionArr = dataPermission.split(":");
				if ("00".equals(dataPermissionArr[0])) {
					response.setErrorMsg(XFUNExceptionCode.USER_PRODUCTNOEXIST.getDesin());
					response.setSuccess(false);
					return response;
				}
				String sql = dataPermissionArr[1];
				//权限为个人时，需要查询没有经纪人的用户
				if(sql.indexOf(")") >= 0 && "".equals(dto.getMatch())) {
					sql = sql.replace(")", "");
					sql += " OR cpq.customer_id = -1 )" ;
					dto.setDataPermission(sql);
				} else if("1".equals(dto.getMatch())) {
					//已匹配
					dto.setDataPermission(sql);
				} else if ("2".equals(dto.getMatch())){
					//未匹配
					dto.setDataPermission(" AND cpq.customer_id = -1");
				}
			}
			
			Page<ProjectQuestionnaireInfo> page = service.getCustomerPageInfo(dto, begin, row);
			if(null==page.getRows()){
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response=page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<ProjectQuestionnaireDto> saveInfo(ProjectQuestionnaireDto dto, Long modelId, Long copyId) {
		Response<ProjectQuestionnaireDto> response=new Response<ProjectQuestionnaireDto>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			//判断问卷名称是否重复
			ProjectQuestionnaireDto entity = new ProjectQuestionnaireDto();
			entity.setName(dto.getName());
			entity.setProjectId(dto.getProjectId());
    		entity.setMerchantId(dto.getMerchantId());
    		entity.setDelFlag("0");
			List<ProjectQuestionnaire> list = service.selectListByDto(entity);
			if(list != null && list.size() > 0){
    			response.fail("0000", "该名称已有重复问卷，请更换问卷名称后再保存");
    			return response;
    		}
			//查询项目信息
			Project project = getProject(dto.getProjectId());
			//设置项目权限字段
			dto.setAccessCode(project.getProjectCode());
			//保存项目问卷
			ProjectQuestionnaireDto mDto = service.create(dto);
			if(null==mDto){
				response.fail("80000", "保存数据错误");
				return response;
			}
			//当模板ID不为空时，复制模板问题及答案
			if(modelId != null){
				getModelToProjectQuestion(mDto.getId(), mDto.getProjectId(), modelId);
			}
			//当复制ID不为空时，复制选择的项目问卷
			if(copyId != null){
				copyQuestionnaireQuestion(mDto.getId(), mDto.getProjectId(), copyId);
			}
			response.success(mDto);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}",e);
		}
		return response;
	}
	
	/**
	 * 查询项目信息
	 * @param projectId
	 * @return
	 */
	private Project getProject(Long projectId){
		Project project = projectService.selectById(projectId);
		return project;
	}
	
	/**
	 * 复制模板问题
	 * @param id
	 * @param modelId
	 */
	private void getModelToProjectQuestion(Long id, Long projectId, Long modelId) {
		QuestionnaireQuestionDto entity = new QuestionnaireQuestionDto();
		entity.setQuestionnaireModelId(modelId);
		List<QuestionnaireQuestion> list = questionnaireQuestionService.selectListByDto(entity);
		for(QuestionnaireQuestion qq : list){
			ProjectQuestionDto dto = new ProjectQuestionDto();
			BeanUtils.copyProperties(qq, dto);
			dto.setProjectQuestionnaireId(id);
			dto.setProjectId(projectId);
			ProjectQuestionDto res = projectQuestionService.create(dto);
			getModelToProjectAnswer(res.getId(), qq.getId());
		}
	}
	
	/**
	 * 复制模板答案
	 * @param id
	 * @param copyId
	 */
	private void getModelToProjectAnswer(Long id, Long questionId) {
		QuestionnaireAnswerDto entity = new QuestionnaireAnswerDto();
		entity.setQuestionnaireQuestionId(questionId);
		List<QuestionnaireAnswer> list = questionnaireAnswerService.selectListByDto(entity);
		for(QuestionnaireAnswer qq : list){
			ProjectAnswerDto dto = new ProjectAnswerDto();
			BeanUtils.copyProperties(qq, dto);
			dto.setProjectQuestionId(id);
			projectAnswerService.create(dto);
		}
	}
	
	/**
	 * 复制项目问卷问题
	 * @param id
	 * @param modelId
	 */
	private void copyQuestionnaireQuestion(Long id, Long projectId, Long copyId) {
		ProjectQuestionDto entity = new ProjectQuestionDto();
		entity.setProjectQuestionnaireId(copyId);
		List<ProjectQuestion> list = projectQuestionService.selectListByDto(entity);
		for(ProjectQuestion qq : list){
			ProjectQuestionDto dto = new ProjectQuestionDto();
			BeanUtils.copyProperties(qq, dto);
			dto.setProjectQuestionnaireId(id);
			dto.setProjectId(projectId);
			ProjectQuestionDto res = projectQuestionService.create(dto);
			copyQuestionnaireAswer(res.getId(), qq.getId());
		}
	}
	
	/**
	 * 复制项目问卷答案
	 * @param id
	 * @param copyId
	 */
	private void copyQuestionnaireAswer(Long id, Long copyId) {
		ProjectAnswerDto entity = new ProjectAnswerDto();
		entity.setProjectQuestionId(copyId);
		List<ProjectAnswer> list = projectAnswerService.selectListByDto(entity);
		for(ProjectAnswer qq : list){
			ProjectAnswerDto dto = new ProjectAnswerDto();
			BeanUtils.copyProperties(qq, dto);
			dto.setProjectQuestionId(id);
			projectAnswerService.create(dto);
		}
	}

	@Override
	public ResponseList<ProjectQuestionnaireInfo> findAyalyzeAnswerByDto(ProjectQuestionnaireDto dto) {
		ResponseList<ProjectQuestionnaireInfo> response=new ResponseList<ProjectQuestionnaireInfo>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<ProjectQuestionnaireInfo> list=service.findAyalyzeAnswerByDto(dto);
			if(null==list){
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}",e);
		}
		return response;
	}
	
	@Override
	public ResponseList<ProjectQuestionnaireInfo> getCustomerInfoList(Long projectId, Long questionnaireId) {
		ResponseList<ProjectQuestionnaireInfo> response=new ResponseList<ProjectQuestionnaireInfo>();
		try {
			List<ProjectQuestionnaireInfo> list=service.getCustomerInfoList(projectId, questionnaireId);
			if(null==list){
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}",e);
		}
		return response;
	}
}
